//
//  BHImageOrVideoPreviewViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/7.
//

import UIKit
import AVKit
import Photos

class BHImageOrVideoPreviewViewController: BHBaseViewController {

    // 0默认图片预览   1视频预览
    var previewType: Int = 0
    
    lazy var collectionView: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout.init()
        flowlayout.scrollDirection = .horizontal
        let view = UICollectionView.buildCollectionView(layout: flowlayout)
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)
        view.backgroundColor = .black
        view.isPagingEnabled = true
        view.register(UINib.init(nibName: "BHImageOrVideoItemCell", bundle: nil), forCellWithReuseIdentifier: "BHImageOrVideoItemCell")
        view.register(BHImagePreviewCollectionViewCell.self, forCellWithReuseIdentifier: "BHImagePreviewCollectionViewCell")
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    lazy var avplaer: AVPlayer = {
        let p = AVPlayer.init()
        return p
    }()
    
    lazy var avplayerlayer: AVPlayerLayer = {
        let layer = AVPlayerLayer.init()
        return layer
    }()

    fileprivate var markIndex: IndexPath?

    var sourceArray: [BHImageOrVideoModel] = [] {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    var index: Int = -1 {
        didSet {
            self.collectionView.scrollToItem(at: IndexPath.init(item: index, section: 0), at: .centeredHorizontally, animated: false)
        }
    }
    
    var avModel: BHImageOrVideoModel? {
        didSet {
            if avModel == nil {
                return
            }
            if avModel!.asset == nil {
                if avModel!.videoUrl?.isEmpty == false {
                    let item = AVPlayerItem.init(url: URL.init(string: avModel?.videoUrl ?? "")!)
                    self.avplaer.replaceCurrentItem(with: item)
                    self.avplaer.play()
                }
            }else {
                PHCachingImageManager.init().requestAVAsset(forVideo: avModel!.asset!, options: .none) { (avsset, audioMix, info) in
                    let item = AVPlayerItem.init(asset: avsset!)
                    self.avplaer.replaceCurrentItem(with: item)
                    self.avplaer.play()
                }
            }
        }
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .black
        self.view.addSubview(self.collectionView)
        self.bh_navigationBar.backgroundColor = UIColor.white.withAlphaComponent(0.0)
        self.bh_navigationBar.contain_backView.backgroundColor = UIColor.white.withAlphaComponent(0.0)
        self.bh_navigationBar.title_label.isHidden = true
        
        self.avplayerlayer.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height)
        self.avplayerlayer.player = self.avplaer
        self.view.layer.addSublayer(self.avplayerlayer)
    }
    
    override func backAction() {
        self.dismiss(animated: true, completion: nil)
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return .lightContent
        }
    }
}


extension BHImageOrVideoPreviewViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.sourceArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.width, height: UIScreen.height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return .zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
}

extension BHImageOrVideoPreviewViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.sourceArray[indexPath.row]
        if model.sourceType == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHImagePreviewCollectionViewCell", for: indexPath) as! BHImagePreviewCollectionViewCell
            cell.model = model
            cell.dissMissTapActBlock = { [weak self] in
                self?.dismiss(animated: true, completion: nil)
            }
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHImageOrVideoItemCell", for: indexPath) as! BHImageOrVideoItemCell
            cell.type = 1
            cell.model = model
    
            return cell
        }
    }
}
